<template>
  <!-- 搜索区域 -->
  <div style="height: 10vh; background-color: #fff; padding: 10px 20px;">
    <el-card style="height: 100%;">
      <el-form :inline="true" class="searchForm">
        <!-- 停车场名称使用 parklot 数据 -->
        <el-form-item label="停车场名称:">
          <el-select v-model="searchForm.parkName" placeholder="请选择停车场名称" filterable clearable>
            <el-option v-for="park in parkList" :key="park.value" :label="park.label" :value="park.label" />
          </el-select>
        </el-form-item>

        <!-- 车牌号 -->
        <el-form-item label="车牌号:">
          <el-select v-model="searchForm.carCode" placeholder="请选择车牌号" filterable clearable>
            <el-option v-for="car in parkData.carCodes" :key="car.value" :label="car.label" :value="car.value" />
          </el-select>
        </el-form-item>
      </el-form>

      <el-form :inline="true">
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" :loading="loading" @click="queryForm">查询</el-button>
          <el-button type="primary" @click="newDialog">新建</el-button>
          <el-button
              :disabled="selectedRows.length === 0"
              :style="{ backgroundColor: selectedRows.length === 0 ? '#ffcccc' : '#ff4d4f', color: '#fff' }"
              @click="batchDelete"
          >
            删除
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <!-- 弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogForm.visible" width="40vh">
    <el-form label-width="10vh" label-position="left" class="dialog-form">
      <el-row style="display: flex; flex-direction: column; align-items: center;" :gutter="10">
        <el-col :span="24">
          <el-form-item label="停车场名称:">
            <el-select v-model="dialogForm.parkName" placeholder="请选择停车场名称" filterable>
              <el-option v-for="park in parkList" :key="park.value" :label="park.label" :value="park.label" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="车牌号:">
            <el-input placeholder="请输入车牌号" v-model="dialogForm.carCode" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="违规原因:">
            <el-input placeholder="请输入违规原因" v-model="dialogForm.reason" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div style="display: flex; justify-content: center; gap: 20px;">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveDialog">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 列表和分页区域 -->
  <el-card style="margin: 20px; height: 70vh; display: flex; flex-direction: column;">
    <!-- 表格容器 -->
    <div class="table-container">
      <el-table
          :data="showList"
          border
          v-loading="loading"
          @selection-change="handleSelectionChange"
          ref="tableRef"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="parkName" label="停车场名称" align="center" />
        <el-table-column prop="carCode" label="车牌号" align="center" />
        <el-table-column prop="reason" label="违规原因" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <el-table-column prop="updateTime" label="更新时间" align="center" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="editRow(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页容器 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { logOperation } from '@/utils/log';

const API_URL = import.meta.env.VITE_API_BASE_URL;

const searchForm = ref({
  parkName: '',
  carCode: '',
  status: ''
});

const showList = ref([]);
const parkData = ref({
  carCodes: []
});

const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const parkList = ref([]);

const dialogTitle = ref('新增黑名单');
const dialogForm = ref({
  visible: false,
  id: null,
  parkName: '',
  carCode: '',
  reason: '',
  createTime: '',
  updateTime: ''
});

const selectedRows = ref([]);
const tableRef = ref(null);

const queryForm = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm.value,
      page: currentPage.value,
      size: pageSize.value
    };
    const { data } = await axios.get(`${API_URL}/v1/blacklist/select`, { params });
    if (data.code === 2000) {
      showList.value = data.response || [];
      total.value = data.total || 0; // Use total from backend
      updateOptions(data.response);
      ElMessage.success('数据加载成功');
    } else {
      ElMessage.error(`数据加载失败: ${data.response?.message || '未知错误'}`);
      showList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('查询错误:', error);
    ElMessage.error('请求异常');
    showList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const updateOptions = (blacklist) => {
  const uniqueCarCodes = new Map();
  blacklist.forEach(item => {
    if (item.carCode) uniqueCarCodes.set(item.carCode, item.carCode);
  });
  parkData.value.carCodes = Array.from(uniqueCarCodes, ([value, label]) => ({ value, label }));
};

const fetchParkOptions = async () => {
  try {
    const { data } = await axios.get(`${API_URL}/v1/parklot/select`, { params: { size: 10000 } });
    if (data.code === 2000) {
      parkList.value = data.response.map(park => ({
        value: park.parkName,
        label: park.parkName
      }));
    } else {
      ElMessage.error('停车场选项加载失败');
    }
  } catch (error) {
    console.error('停车场选项加载错误:', error);
    ElMessage.error('选项加载异常');
  }
};

const resetForm = () => {
  searchForm.value = {};
  currentPage.value = 1;
  ElMessage.success('已重置筛选条件');
  queryForm();
};

const newDialog = () => {
  dialogForm.value = {
    visible: true,
    id: null,
    parkName: '',
    carCode: '',
    reason: '',
    createTime: '',
    updateTime: ''
  };
  dialogTitle.value = '新增黑名单';
};

const saveDialog = async () => {
  try {
    const url = dialogForm.value.id ? `${API_URL}/v1/blacklist/update` : `${API_URL}/v1/blacklist/insert`;
    const method = dialogForm.value.id ? 'put' : 'post';
    const { data } = await axios({ method, url, data: dialogForm.value });

    if (data.code === 2000) {
      ElMessage.success(dialogForm.value.id ? '更新成功' : '新建成功');
      dialogForm.value.visible = false;
      await queryForm();
      await logOperation('黑名单管理', `${dialogForm.value.id ? '更新' : '新建'}黑名单 ${dialogForm.value.carCode}`);
    } else if (data.code === 4000) {
      ElMessage.warning(data.response?.message || '记录已存在');
    } else {
      ElMessage.error(`保存失败: ${data.response?.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('保存错误:', error);
    ElMessage.error('请求异常');
  }
};

const closeDialog = () => {
  ElMessageBox.confirm('您确认要关闭本弹窗吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        dialogForm.value.visible = false;
      })
      .catch(() => {});
};

const editRow = (row) => {
  console.log('编辑行数据:', row);
  dialogTitle.value = '编辑黑名单';
  dialogForm.value = {
    visible: true,
    id: row.id,
    parkName: row.parkName,
    carCode: row.carCode,
    reason: row.reason,
    status: row.status,
    createTime: row.createTime,
    updateTime: row.updateTime
  };
};

const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

const deleteBlacklists = async (rows) => {
  const isBatch = Array.isArray(rows);
  const count = isBatch ? rows.length : 1;
  const ids = isBatch ? rows.map(row => row.id) : [rows.id];
  const confirmMessage = isBatch
      ? `您确认要删除 ${count} 个黑名单记录吗?`
      : '您确认要删除此黑名单记录吗?';

  try {
    await ElMessageBox.confirm(confirmMessage, '删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const url = isBatch ? `${API_URL}/v1/blacklist/batchDelete` : `${API_URL}/v1/blacklist/delete/${ids[0]}`;
    const method = isBatch ? 'post' : 'delete';
    const requestData = isBatch ? { ids } : null;

    const { data } = await axios({
      method,
      url,
      data: requestData
    });

    if (data.code === 2000) {
      ElMessage.success(isBatch ? '批量删除成功' : '删除成功');
      await queryForm();

      const logRows = isBatch ? rows : [rows];
      for (const row of logRows) {
        await logOperation('黑名单管理', `删除黑名单 ${row.carCode}`);
      }

      if (isBatch) {
        selectedRows.value = [];
        tableRef.value.clearSelection();
      }
    } else {
      ElMessage.error(`删除失败: ${data.response?.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('删除错误:', error);
    ElMessage.error('请求异常');
  }
};

const deleteRow = async (row) => {
  await deleteBlacklists(row);
};

const batchDelete = async () => {
  if (selectedRows.value.length === 0) return;
  await deleteBlacklists(selectedRows.value);
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryForm();
};

onMounted(() => {
  queryForm();
  fetchParkOptions();
});
</script>

<style scoped>
.searchForm :deep(.el-select) {
  width: 20vh;
}

.dialog-form :deep(.el-input) {
  width: 20vh;
}

.dialog-form :deep(.el-select) {
  width: 20vh;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px; /* 预留分页空间 */
}

/* 分页容器样式 */
.pagination-container {
  padding: 10px 20px;
  text-align: center;
  background-color: #fff;
  min-height: 60px; /* 确保分页区域有足够高度 */
}
</style>